class GridsModalDatatable
  delegate :params, :session, :raw, :link_to, :number_to_currency, :best_in_place, to: :@view

  def initialize(view, current_user)
    @view = view
    @current_user = current_user
  end

  def as_json(options = {})
    {
      draw: params[:sEcho].to_i,
      recordsTotal: fetch_data_count,
      recordsFiltered: fetch_data_count,
      data: aa_data
    }
  end

  private

  def aa_data
    search_scope.order("#{sort_column} #{sort_direction}").skip(skip_num).limit(per_page).map do |record|
      {
        id: record.id.to_s,
        code: record.code,
        name: record.name,
        created_at: record.created_at.strftime('%F %T')
      }
    end
  end

  def fetch_data_count
    @data_count ||= search_scope.count
  end

  def search_scope
    search_params = {}
    s_search      = params[:sSearch]
    search_params = { '$or' => [{ code: /#{s_search}/ }, { name: /#{s_search}/ }] } if s_search.present?
    Grid.where(search_params)
  end

  def skip_num
    (params[:iDisplayStart].to_i / per_page) * per_page
  end

  def per_page
    params[:iDisplayLength].to_i.positive? ? params[:iDisplayLength].to_i : 25
  end

  def sort_column
    columns = %w(code name created_at)
    columns[params[:iSortCol_0].to_i]
  end

  def sort_direction
    params[:sSortDir_0] == 'desc' ? 'desc' : 'asc'
  end
end
